package com.hqyj.javaSpringBoot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Description：ParamFilter
 * 删除请求中的 “fuck” 字符串
 * @Author ：Cwd
 * @Date ：2021/8/23 10:02
 */
@WebFilter(filterName = "paramFilter", value = {"/*"})
public class ParamFilter implements Filter {

    private final static Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("==== Init Filter ====");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("==== Do Filter ====");
        HttpServletRequest re = (HttpServletRequest) req;
        HttpServletResponse res = (HttpServletResponse) resp;

        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(re){
            @Override
            public String getParameter(String name) {
                String value = super.getParameter(name);
                if (StringUtils.isNotBlank(value)){
                    value = value.replaceAll("fuck","***");
                }
                return value;
            }

            @Override
            public String[] getParameterValues(String name) {
                String values = super.getParameter(name);
                //Stream api:数组 ---- list ---- 处理数据 ---- 转化为数组
                // :: 相当于静态方法
                return Arrays.asList(values)
                        .stream()
                        .map(item -> item.replaceAll("fuck","***"))
                        .toArray(String[] :: new);
            }
        };
        chain.doFilter(wrapper,res);
    }

    @Override
    public void destroy() {
        LOGGER.debug("==== Do Destroy ====");
    }
}
